import { city, hotCity } from '@/apis/city'
const state = {
  city: {
    label: '杭州',
    value: 'AREA|19b39d4f-8a36-d6f8',
    pinyin: 'hangzhou',
    short: 'hz'
  },
  cityList: [],
  hotCity: []
}
const getters = {
  indexList () {
    const arr = [...new Set(state.cityList.map(item => {
      return item.short[0].toUpperCase()
    }))]
    arr.unshift('#', '热')
    return arr
  },
  filterList () {
    const list = getters.indexList()
    return list.map(item => {
      const arr = []
      state.cityList.forEach(ite => {
        if (item === ite.short[0].toUpperCase()) {
          arr.push(ite)
        }
      })
      return arr
    }).filter(item => item.length > 0)
  }
}
const mutations = {
  changeCity (state, payload) {
    state.city = payload
  },
  setCityList (state, payload) {
    state.cityList = payload
  },
  setHotCity (state, payload) {
    state.hotCity = payload
  }
}
const actions = {
  async getCity (ctx) {
    const { data } = await city({ level: 1 })
    const list = data.body.sort((a, b) => {
      const x = a.short.toLowerCase()
      const y = b.short.toLowerCase()
      if (x < y) {
        return -1
      } else if (x > y) {
        return 1
      }
      return 0
    })
    ctx.commit('setCityList', list)
    const res = await hotCity()
    ctx.commit('setHotCity', res.data.body)
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
